import type { Ref } from "vue"
import { watch, nextTick } from "vue"

/** 
   @param visible 模态框显隐的状态
   @param title 模态框标题，唯一标识该模态框。当传递了visible，该属性必传
   @remark 如果不传visible，请自行调用返回的方法来设置和解除拖拽功能
   @description 使得模态框可以拖拽。拖动有时不稳是因为头部高度小的原因
**/
export function useModalDraggable(visible?: Ref<boolean>,title?: string) {
    if (visible && title)
    watch(visible, (v) => {
      // console.log(v)
      if (v) setDraggable(title)
      else removeDraggable()
    })
   return { setDraggable, removeDraggable }
}


const modalClassSelector = ".ant-modal"
const headerClassSelector = ".ant-modal-header"
const wrapClassSelector=".ant-modal-wrap"
let modal: HTMLElement | null          // 这边获取到的modal是调用处模态框的modal
let header: HTMLElement | null         // 调用处模态框的header
let wrap: HTMLElement | null    // 调用处模态框的wrap
const titles:string[]=[]          // 绑定了事件的模态框标题集合
let pressToLeftLength = 0
let pressToTopLength = 0
let maxOffsetLeft = 0
let maxOffsetTop = 0
let isPress = false

function mousedown(e: MouseEvent) {
  if(!modal || !header || !wrap) init(titles[titles.length-1])

  isPress = true

  pressToLeftLength = e.clientX - modal!.offsetLeft
  pressToTopLength = e.clientY - modal!.offsetTop

  maxOffsetLeft = document.documentElement.clientWidth - (modal!.offsetWidth + 2)
  // 24是modal的内边距
  maxOffsetTop = document.documentElement.clientHeight - (modal!.offsetHeight-24+2)
}

function mousemove(e: MouseEvent) {
  if (isPress) {
    e.preventDefault()
    if (modal!.style.userSelect != "none") modal!.style.userSelect = "none"
    if (modal!.style.margin != '0px') modal!.style.margin = '0px'

    const nextLeft = e.clientX - pressToLeftLength
    const nextTop = e.clientY - pressToTopLength

    if (nextLeft > 0 && nextLeft <= maxOffsetLeft)
      modal!.style.left = nextLeft + 'px'
    if (nextTop > 0 && nextTop <= maxOffsetTop)
      modal!.style.top = nextTop + 'px'
  }
}

function mouseup(e: MouseEvent) {
  if(modal)
  modal.style.userSelect = "unset"
  isPress = false
}

/** 
    @description  为调用处的模态框添加拖拽功能，建议在模态框打开时添加
**/
function setDraggable(title: string) {
  nextTick(() => {
     init(title)
  })
}

/** 
   @description  移除拖拽功能
**/
function removeDraggable() {
  if (header && modal&& wrap) {
    header.style.cursor = "unset"
    // modal.style.left=''   // 目前没找到方法回到初始偏移，只有回到初始偏移才能添加回居中属性，否则有问题
    // modal.style.top=''
    //if(wrap.getAttribute('centered')) wrap.classList.add('ant-modal-centered') 
    header.removeEventListener("mousedown", mousedown)
    header.removeEventListener("mousemove", mousemove)
    wrap.removeEventListener("mouseup", mouseup)
    modal=null
    header=null
    wrap=null
    titles.pop()
    //console.log("成功移除拖拽功能")
  }
}

/**
 * @description 获取当前模态框内的相关dom和并为其绑定事件
 * @param title 
 */
function init(title:string){
  const modals: any = document.querySelectorAll(modalClassSelector)
  const headers: any = document.querySelectorAll(headerClassSelector)
  const wraps:any=document.querySelectorAll(wrapClassSelector)
  

  if (headers.length && modals.length) {
   // console.log(headers)
   
    headers.forEach((v: HTMLElement, index: number) => {
      if (v.innerText == title) {
        header = v
        modal = modals[index]
        wrap=wraps[index]
      }
    })
  
    //console.log(header,modal)
    header!.style.cursor = "move"

    titles.push(title)
    
    // if(wrap.classList.contains('ant-modal-centered'))
    wrap!.classList.remove('ant-modal-centered')    // 解决centered属性与拖拽功能冲突的问题，居中属性将失效
    wrap!.setAttribute('centered','true')

    header!.addEventListener("mousedown", mousedown)
    header!.addEventListener("mousemove", mousemove)
    wrap!.addEventListener("mouseup", mouseup)
  }
  else {
    console.error('请确保模态框打开后再调用 setDraggable！')
  }
}


